package role

import (
	"context"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gtime"

	v1 "myapp/api/role/v1"
	"myapp/internal/model"
	"myapp/internal/service"
)

func (c *ControllerV1) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {

	return nil, gerror.NewCode(gcode.CodeNotImplemented)
}
func (c *ControllerV1) Detail(ctx context.Context, req *v1.DetailReq) (res *v1.DetailRes, err error) {
	role, err := service.Role().GetOne(ctx, req.Id)
	if err != nil {
		return nil, gerror.New("没有找到这条纪录")
	}
	res = &v1.DetailRes{
		RoleDetail: v1.RoleDetail{
			Name:   role.Name,
			Pid:    role.Pid,
			Status: role.Status,
			Remark: role.Remark,
		},
	}
	return res, nil
}
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
	id, err := service.Role().Create(ctx, &model.RoleInput{
		Name:       req.Name,
		Pid:        req.Pid,
		Status:     req.Status,
		Remark:     req.Remark,
		CreateTime: gtime.Now(),
	})
	if err != nil {
		return nil, err
	}
	res = &v1.CreateRes{Id: id}
	return res, nil
}
func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
	err = service.Role().Update(ctx, &model.RoleInput{
		Id:         req.Id,
		Name:       req.Name,
		Pid:        req.Pid,
		Status:     req.Status,
		Remark:     req.Remark,
		CreateTime: gtime.Now(),
	})
	if err != nil {
		return nil, err
	}
	return &v1.UpdateRes{}, err
}
func (c *ControllerV1) Delete(ctx context.Context, req *v1.DeleteReq) (res *v1.DeleteRes, err error) {
	nums, err := service.Role().Delete(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &v1.DeleteRes{Nums: nums}, err
}

// 为用户分配角色
func (c *ControllerV1) AddMember(ctx context.Context, req *v1.AddMemberReq) (res *v1.AddMemberRes, err error) {
	id, err := service.Role().AddMember(ctx, req.RoleId, req.MemberId)
	if err != nil {
		return nil, err
	}
	return &v1.AddMemberRes{Id: id}, err
}

func (c *ControllerV1) DeleteMember(ctx context.Context, req *v1.DeleteMemberReq) (res *v1.DeleteMemberRes, err error) {
	nums, err := service.Role().RemoveMember(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &v1.DeleteMemberRes{Nums: nums}, err
}
